<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定时器测试</title>
    <style>
        div {
            width: 800px;
            margin: 100px auto;
        }

        #show_time {
            color: red;
            font-size: 28px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div>
        <h1>WEB前端开发——王育才</h1>
        <span id="show_time"></span>
        <hr />
        <button onclick="stop()">停止</button>
    </div>
    <script>
        function showTime() {
            let myTime = new Date();
            let hour = myTime.getHours();
            let minite = myTime.getMinutes() < 10 ? '0' + myTime.getMinutes() : myTime.getMinutes();
            let second = myTime.getSeconds() < 10 ? '0' + myTime.getSeconds() : myTime.getSeconds();

            let obj = document.getElementById("show_time");
            obj.innerHTML = hour + ":" + minite + ":" + second;
        }

        timer = setInterval(() => {
            showTime();
        }, 1000);

        function stop() {
            if (timer) {
                clearInterval(timer);
                timer = undefined;
            }
        }

        showTime();

    </script>
</body>

</html>